# -*- coding: utf-8 -*-
from scapy.layers.l2 import Ether, ARP
from scapy.sendrecv import srp


def neibor_get(net, timeout, iface):
    '''
    邻居发现
    :param net:
    :param timeout:
    :param iface:
    :return: 响应arp请求的邻居
    '''
    ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") /
                     ARP(pdst=net), timeout=timeout, iface=iface)
    return [recv[ARP].psrc for _, recv in ans]


def neibor_update(net, timeout, iface=None):
    '''
    邻居更新
    :return:
    '''
    neibors = set()  # 邻居存储
    while True:
        new_neibors = set(neibor_get(net, timeout, iface))  # 新的邻居状态
        unchange_neibors = new_neibors.intersection(neibors)  # 求交集，及不变的邻居
        # connect_neibors = new_neibors - unchange_neibors  # 新加入的邻居
        connect_neibors = new_neibors  # 服务器采用惰性更新时使用，每次都报告发现的全部邻居
        lost_neibots = neibors - unchange_neibors  # 失去连接的邻居
        neibors = new_neibors  # 更新邻居
        yield connect_neibors, lost_neibots


if __name__ == '__main__':
    print(neibor_get("192.168.66.0/24"))
